/**
 * Copyright (c) 2020 wuchenxi
 * walter-blog is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 * <p>
 * <p>
 * Mulan Permissive Software License，Version 2
 * <p>
 * Mulan Permissive Software License，Version 2 (Mulan PSL v2)
 * January 2020 http://license.coscl.org.cn/MulanPSL2
 */
package com.walter.blog.business.content.controller;

import cn.hutool.core.util.StrUtil;
import com.walter.aliyun.oss.deleteobject.OssDelete;
import com.walter.auth.SecurityUtil;
import com.walter.auth.config.user.BlogUser;
import com.walter.blog.business.content.service.ContentService;
import com.walter.blog.business.content.service.UserContentService;
import com.walter.db.pojo.Content;
import com.walter.db.pojo.UserContent;
import com.walter.dto.content.DraftDTO;
import com.walter.response.ResponseKit;
import com.walter.vo.content.ContentListVO;
import com.walter.vo.page.PageVO;
import io.swagger.annotations.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wuchenxi
 * @date 2020-08-08 10:42:43
 */
@Api(tags = "文章管理")
@Validated
@RestController
@RequestMapping("/content")
public class ContentController {

    @Resource
    private ContentService contentService;

    @Resource
    private UserContentService userContentService;

    @Resource
    private HttpSession httpSession;

    @ApiOperation(value = "发表文章")
    @ApiResponses(value = {
            @ApiResponse(code = 403, message = "用户还未登录"),
            @ApiResponse(code = 200, message = "发表成功")
    })
    @PostMapping("/add_content")
    @PreAuthorize("isAuthenticated()")
    public ResponseKit<Object> addContent(@Valid Content content, @ApiParam(name = "分类id", required = false) String categoryId) {
        return contentService.addContent(content, categoryId);
    }

    @ApiOperation(value = "获取所有公开文章")
    @GetMapping("/list_contents")
    @PreAuthorize("permitAll()")
    public ResponseKit<PageVO<ContentListVO>> listContents(@ApiParam(name = "pageNum", value = "当前页", defaultValue = "1")
                                                           @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                                           @ApiParam(name = "pageSize", value = "每页数据量", defaultValue = "20")
                                                           @RequestParam(required = false, defaultValue = "20") Integer pageSize,
                                                           @ApiParam(name = "content", value = "搜索内容") String content) {
        if (StringUtils.isEmpty(content)) {
            content = null;
        }
        content = StringUtils.trim(content);
        return contentService.listContents(pageNum, pageSize, content);
    }

    @ApiOperation(value = "获取我自己所有文章")
    @ApiResponses(value = {
            @ApiResponse(code = 403, message = "用户还未登录")
    })
    @GetMapping("/list_my_contents")
    @PreAuthorize("isAuthenticated()")
    public ResponseKit<PageVO<ContentListVO>> listMyContents(@ApiParam(name = "pageNum", value = "当前页", defaultValue = "1")
                                                             @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                                             @ApiParam(name = "pageSize", value = "每页数据量", defaultValue = "20")
                                                             @RequestParam(required = false, defaultValue = "20") Integer pageSize,
                                                             @ApiParam(name = "content", value = "搜索内容") String content) {
        if (StringUtils.isEmpty(content)) {
            content = null;
        }
        content = StringUtils.trim(content);
        return contentService.listMyContents(pageNum, pageSize, content);
    }

    @ApiOperation(value = "保存草稿")
    @ApiResponse(code = 200, message = "保存成功！")
    @PostMapping("/saveDraft")
    @Transactional(rollbackFor = Exception.class)
    @PreAuthorize("isAuthenticated()")
    public ResponseKit<Object> saveDraft(@Valid DraftDTO dto) {

        Content content = new Content();
        if (StringUtils.isEmpty(dto.getId())) {
            BeanUtils.copyProperties(dto, content);
            content.setState(1);
            content.setCreateTime(new Date());
            content.setUpdateTime(new Date());
            contentService.save(content);

            BlogUser user = SecurityUtil.getBlogUser();
            userContentService.save(UserContent.builder()
                    .userId(user.getId())
                    .contentId(content.getId())
                    .build());
        } else {
            BeanUtils.copyProperties(dto, content);
            content.setUpdateTime(new Date());
            content.setState(1);
            contentService.updateById(content);
        }

        Map<String, String> map = new HashMap<>(16);
        map.put("id", content.getId());
        return ResponseKit.success(map);
    }

    @ApiOperation(value = "查询指定文章信息")
    @GetMapping("/get_content")
    @PreAuthorize("permitAll()")
    public ResponseKit<Content> getContent(@ApiParam(name = "id", value = "文章id", required = true) String id) {
        if (StringUtils.isEmpty(id)) {
            return ResponseKit.error(HttpStatus.BAD_REQUEST.value(), "id can't be null!");
        }
        return contentService.getContent(id);
    }

    @ApiOperation(value = "查询需要编辑文章信息")
    @GetMapping("/edit/get_content")
    @PreAuthorize("isAuthenticated()")
    public ResponseKit<Content> getDetailContent(@ApiParam(name = "id", value = "文章id", required = true) String id) {
        return this.getContent(id);
    }


    @ApiOperation(value = "验证用户是否能够编辑当前文章")
    @ApiResponses({
            @ApiResponse(code = 200, message = "有权限编辑"),
            @ApiResponse(code = 403, message = "不可编辑")
    })
    @GetMapping("/can_edit")
    @PreAuthorize("permitAll()")
    public ResponseKit<Object> canEdit(@ApiParam(name = "id", value = "文章id", required = true) String id) {
        return contentService.canEdit(id);
    }


    @ApiOperation("删除文章")
    @ApiResponses({
            @ApiResponse(code = 200, message = "删除成功"),
            @ApiResponse(code = 403, message = "不可删除")
    })
    @DeleteMapping("/del_content")
    @PreAuthorize("isAuthenticated()")
    public ResponseKit<Object> del(@ApiParam(name = "id", value = "文章id", required = true) String id) {
        return contentService.del(id);
    }

    @ApiOperation("上传图片")
    @PreAuthorize("isAuthenticated()")
    @PostMapping("/upload_img")
    public ResponseKit<Object> uploadImg(MultipartFile file) {
        return contentService.uploadImg(file);
    }

    @ApiOperation("删除图片")
    @PreAuthorize("isAuthenticated()")
    @PostMapping("/del_img")
    public ResponseKit<Object> delImg(@ApiParam(name = "url", value = "图片url", required = true) String url) {
        if (StrUtil.isEmpty(url)) {
            return ResponseKit.success();
        }
        OssDelete.deleteObject(url);
        return ResponseKit.success();
    }

    @ApiOperation("当前文章绑定的类型")
    @PreAuthorize("isAuthenticated()")
    @GetMapping("/category")
    public ResponseKit<String> category(@ApiParam(name = "文章id", required = true) String contentId) {
        return contentService.category(contentId);
    }
}
